package com.itheima.listdemo;

import java.util.ArrayList;

public class ArrayListDemo7 {
    public static void main(String[] args) {
        //1.创建集合对象
        ArrayList<User> list = new ArrayList<>();

        //2.创建用户对象
        User u1 = new User("heima001", "zhangsan", "123456");
        User u2 = new User("heima002", "lisi", "1234");
        User u3 = new User("heima003", "wangwu", "1234qwer");

        //3.把用户对象添加到集合当中
        list.add(u1);
        list.add(u2);
        list.add(u3);

        //4.调用方法，通过id获取对应的索引
        int index = getIndex(list, "heima001");
        System.out.println(index);

        //5.调用方法，通过索引判断id是否存在
        boolean result = contains(list, "heima001");
        System.out.println(result);

    }

    public static int getIndex(ArrayList<User> list, String id) {
        //遍历集合得到每一个元素
        for (int i = 0; i < list.size(); i++) {
            User u = list.get(i);
            String uid = u.getId();
            if (uid.equals(id)) {
                return i;
            }
        }
        //因为只有当集合里面所有的元素都比较完了，才能断定id是不存在的。
        return -1;
    }

    public static boolean contains(ArrayList<User> list, String id) {
        //调用getIndex方法，获取索引
        int index = getIndex(list, id);
        return index >= 0;
    }
}
